//
//  PxOilNetSession.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxGlobal.h"

PxGlobal *shared;

@implementation PxGlobal

+ (instancetype)shared
{
    if (shared == nil)
    {
        @synchronized(self)
        {
            if (shared == nil)
            {
                shared = [[self alloc] init];
                shared.plistPath = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
                shared.plist = [[NSDictionary alloc] initWithContentsOfFile:shared.plistPath];
            }
        }
    }
    return shared;
}

+(NSString *)getConfig:(NSString *)key
{
    NSString *value = nil;
    value = [[PxGlobal shared].plist objectForKey:key];
    
    return value;
}

+ (CGFloat)getBaseHeight:(BOOL)withBottom
{
    CGFloat baseHeight = TITLE_HEIGHT;
    
    if ([LLYTSmallUtil iOSBigVersion]>=6.5) {
        baseHeight += STATUSBAR_HEIGHT;
    }
    if (withBottom) {
        baseHeight += TABBAR_HEIGHT;
    }
    
    return baseHeight;
}

+ (CGFloat)getCustomerWidth:(CGFloat)baseWidth
{
    CGFloat retWidth = baseWidth;
    if (is_iPhone6) {
        retWidth = baseWidth*375/320;
    } else if (is_iPhone6P) {
        retWidth = baseWidth*414/320;
    } else if (is_iPhone4) {
        retWidth = baseWidth*320/320;
    }
    return retWidth;
}

+ (CGFloat)getCustomerHeight:(CGFloat)baseHeight
{
    CGFloat retHeight = baseHeight;
    if (is_iPhone6) {
        retHeight = baseHeight*667/568;
    } else if (is_iPhone6P) {
        retHeight = baseHeight*736/568;
    } else if (is_iPhone4) {
        retHeight = baseHeight*480/568;
    }
    return retHeight;
}

+(UIImage*) imageWithColor:(UIColor*)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

// Duplicate UIView
+ (id)duplicate:(UIView*)view
{
    NSData *tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
    id newView = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
    return newView;
}

+(void)appendData:(id)value andKey:(NSString *)key
{
    NSString *data = [PxGlobal getData:key];
    if (data.length == 0) {
        data = value;
    } else {
        NSString *result = value;
        NSArray *arrs = [data componentsSeparatedByString:@","];
        int count = 0;
        for (NSString *tmp in arrs) {
            if (count > 20)
                break;
            if (![tmp isEqualToString:value]) {
                count ++;
                result = [NSString stringWithFormat:@"%@,%@", result, tmp];
            }
        }
        data = result;
    }
    [PxGlobal saveData:data andKey:key];
}

+(void)saveData:(id)value andKey:(NSString *)key
{
    NSUserDefaults *userPrefs = [NSUserDefaults standardUserDefaults];
    [userPrefs setObject:value forKey:key];
    [userPrefs synchronize];
}

+(id)getData:(NSString *)key
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

+(void)removeData:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}

+(void)clearAllUserDefaultsData
{
    NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
}

+(NSString *)getDicValue:(NSString *)key fromDic:(NSDictionary *)dic
{
    NSString *value = dic[key];
    return value==nil?@"":value;
}

+(NSMutableDictionary *)getDicFromFMResultSet:(FMResultSet *)set
{
    if (set) {
        return [NSMutableDictionary dictionaryWithObjectsAndKeys:[set stringForColumn:@"id"], @"id",
                                                   [set stringForColumn:@"areaCode"], @"areaNum",
                                                   [set stringForColumn:@"expressCompany"], @"expressCompany",
                                                    [set stringForColumn:@"phone"], @"phone",
                                                    [set stringForColumn:@"payFreight"], @"payFreight",
                                                    [set stringForColumn:@"payment"], @"payment",
                                                    [set stringForColumn:@"waybillNo"], @"waybillNo",
                                                    [set stringForColumn:@"sendTime"], @"sendTime",
                                                    nil];
    } else
        return [[NSMutableDictionary alloc] init];
}

+(void)openDB
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *fileName = [path stringByAppendingPathComponent:@"wenwen.sqlite"];
    LLDLog(@"%@", fileName);
    // 1.获得数据库对象
    FMDatabase *db = [FMDatabase databaseWithPath:fileName];
    // 2.打开数据库
    if ([db open]) {
        [PxGlobal shared].db = db;
        LLDLog(@"打开成功");
        // 2.1创建表
        BOOL success =  [db executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, areaCode TEXT NOT NULL, expressCompany TEXT NOT NULL, phone TEXT NOT NULL, payFreight TEXT NOT NULL, payment TEXT NOT NULL, waybillNo TEXT NOT NULL, sendTime TEXT NOT NULL);", TABLE_SCHOOL]];
        if (success) {
            LLDLog(@"创建【t_school】表成功");
        }else
        {
            LLDLog(@"创建【t_school】表失败");
        }
        success =  [db executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, areaCode TEXT NOT NULL, expressCompany TEXT NOT NULL, phone TEXT NOT NULL, payFreight TEXT NOT NULL, payment TEXT NOT NULL, waybillNo TEXT NOT NULL, sendTime TEXT NOT NULL);", TABLE_APARTMENT]];
        if (success) {
            LLDLog(@"创建【t_apartment】表成功");
        }else
        {
            LLDLog(@"创建【t_apartment】表失败");
        }
        [db close];
    }else
    {
        LLDLog(@"打开失败");
    }
}

+(NSMutableDictionary *)selectTable:(NSString *)tableName withRowId:(NSString *)rowId
{
    [[PxGlobal shared].db open];
    FMResultSet *set = [[PxGlobal shared].db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ where id = '%@' ORDER BY id desc;", tableName, rowId]];
    NSMutableArray *arrays = [NSMutableArray new];
    while (set.next) {
        NSMutableDictionary *dic = [PxGlobal getDicFromFMResultSet:set];
        [arrays addObject:dic];
    }
    [[PxGlobal shared].db close];
    if (arrays.count > 0)
        return arrays[0];
    else
        return nil;
}

+(NSMutableArray *)selectTable:(NSString *)tableName withData:(NSString *)waybillNo
{
    if (waybillNo && waybillNo.length == 0)
        return nil;
    [[PxGlobal shared].db open];
    FMResultSet *set;
    if (waybillNo) {
        set = [[PxGlobal shared].db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ where waybillNo = '%@' ORDER BY id desc;", tableName, waybillNo]];
    } else {
        set = [[PxGlobal shared].db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY id desc;", tableName]];
    }
    NSMutableArray *arrays = [NSMutableArray new];
    while (set.next) {
        NSMutableDictionary *dic = [PxGlobal getDicFromFMResultSet:set];
        [arrays addObject:dic];
    }
    [[PxGlobal shared].db close];
    return arrays;
}

+(BOOL)updateTable:(NSString *)tableName withData:(NSDictionary *)dic
{
    if (![PxGlobal shared].db || !dic)
        return NO;
    [[PxGlobal shared].db open];
    BOOL success = [[PxGlobal shared].db executeUpdate:[NSString stringWithFormat:@"UPDATE %@ SET areaCode = ?, expressCompany = ?, phone = ?, payFreight = ?, payment = ?, waybillNo = ?, sendTime = ? WHERE id = ?", tableName],
                    [PxGlobal getDicValue:@"areaCode" fromDic:dic],
                    [PxGlobal getDicValue:@"expressCompany" fromDic:dic],
                    [PxGlobal getDicValue:@"phone" fromDic:dic],
                    [PxGlobal getDicValue:@"payFreight" fromDic:dic],
                    [PxGlobal getDicValue:@"payment" fromDic:dic],
                    [PxGlobal getDicValue:@"waybillNo" fromDic:dic],
                    [PxGlobal getDicValue:@"sendTime" fromDic:dic],
                    [PxGlobal getDicValue:@"id" fromDic:dic]];// 注意只能拼接对象类型
    [[PxGlobal shared].db close];
    if (!success) {
        LLDLog(@"添加失败");
    }else
    {
        LLDLog(@"添加成功");
    }
    return success;
}

+(int)insertOrUpdateTable:(NSString *)tableName withData:(NSDictionary *)dic
{
    
    if (![PxGlobal shared].db || !dic)
        return -1;
    NSMutableArray *arrays = [PxGlobal selectTable:tableName withData:dic[@"waybillNo"]];
    for (NSMutableDictionary *dic in arrays) {
        int index = [dic[@"id"] intValue];
        [PxGlobal deleteTabel:tableName withID:index];
    }
    [[PxGlobal shared].db open];
    BOOL success = [[PxGlobal shared].db executeUpdate:[NSString stringWithFormat:@"INSERT INTO %@(areaCode, expressCompany, phone, payFreight, payment, waybillNo, sendTime) VALUES(?, ?, ?, ?, ?, ?, ?);", tableName],
                                        [PxGlobal getDicValue:@"areaCode" fromDic:dic],
                                        [PxGlobal getDicValue:@"expressCompany" fromDic:dic],
                                        [PxGlobal getDicValue:@"phone" fromDic:dic],
                                        [PxGlobal getDicValue:@"payFreight" fromDic:dic],
                                        [PxGlobal getDicValue:@"payment" fromDic:dic],
                                        [PxGlobal getDicValue:@"waybillNo" fromDic:dic],
                                        [PxGlobal getDicValue:@"sendTime" fromDic:dic]];// 注意只能拼接对象类型
    int rowId = (int)[[PxGlobal shared].db lastInsertRowId];
    [[PxGlobal shared].db close];
    if (!success) {
        rowId = -1;
        LLDLog(@"添加失败");
    }else
    {
        LLDLog(@"添加成功");
    }
    return rowId;
}

+(void)deleteTabel:(NSString *)tableName withID:(int) index
{
    [[PxGlobal shared].db open];
    if (index<0) {
        BOOL success = [[PxGlobal shared].db executeUpdate:[NSString stringWithFormat:@"DELETE FROM %@", tableName]];// 注意只能拼接对象类型
        if (success) {
            LLDLog(@"删除成功");
        }else
        {
            LLDLog(@"删除失败");
        }
    } else {
        BOOL success = [[PxGlobal shared].db executeUpdate:[NSString stringWithFormat:@"DELETE FROM %@ WHERE id='%i'", tableName, index]];// 注意只能拼接对象类型
        if (success) {
            LLDLog(@"删除成功");
        }else
        {
            LLDLog(@"删除失败");
        }
    }
    [[PxGlobal shared].db close];
}

+(int)scanNumber:(NSString *) str
{
    NSScanner *scanner = [NSScanner scannerWithString:str];
    [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
    int number;
    [scanner scanInt:&number];
    
    return number;
}

@end
